/**
 * 
 */

var params;
var token="";
var currentDate;
var selectedMySQLDate;
new datepickr('date', {'dateFormat': 'F d Y'});

var now;
var notifyTimer;
var changeTimer;
	

function onInit()
{
	now = new Date();
	onNewItem();
	
	
	currentDate = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
	
	params = location.search.replace('?', '').split('&').map(function(val){
		  return val.split('=');
		});
	for(var i=0;i<params.length;i++)
	{
		if(params[i][0] == "token")	 
			token = params[i][1];
		else if(params[i][0] == "date")	 
			currentDate = params[i][1];
		
	}
	
	if(token == "")
	{
		window.location.replace("invalid.html");
	}else
	{
		console.log(token);
		testToken();
	}
	
	buildItems(currentDate);
	google.load('visualization', '1', {packages: ['annotatedtimeline']});
	google.setOnLoadCallback(drawVisualization);
	
}

function testToken()
{
	//console.log("Hello Form Post");
	$.ajax({
	      type: "GET",
	      url: "/CalorieCounterService/TestToken.php",
	      data: {
	        token: token
	      },
	      success: function( result ) 
	      {
	        console.log(result);
	      },
	      error: function (xhr, ajaxOptions, thrownError) 
	      {
	     	console.log(thrownError);
	    	window.location.replace("invalid.html");
	      }
	  });
	return false;
}

function onAddItem()
{
	console.log("onAddItem");
	var date = $("#date").val();
	var entryItem = $("#entry").val();
	var calories = $("#calories").val();
	errMessage = validateForm(date, entryItem, calories);
	if(errMessage != null && errMessage.length < 1)
	{
		selectedMySQLDate = getMySQLDate(date);
		
		if(selectedMySQLDate == "-1")
			alert("Invalid Date");
		else
		{
		
			$.ajax({
				  type: "POST",
				  url: "/CalorieCounterService/SaveEntry.php?token=" + token,
				  data: 
				  {
					  date: selectedMySQLDate, 
				      entry: entryItem,
				      calories: calories,
				      notes:  $("#notes").val(),
				      carbs: $("#carbs").val(),
				      entryid: $("#entryid").val()
				  },
			      success: onSuccessSaveItem,
			      error: onSaveError
				  });
			
		}
		
		
		
	}else
	{
		alert(errMessage);
	}
	return false;
}

function validateForm(dt,food,cals )
{
	console.log("validateForm");
	
	if(dt == null || dt.length == 0)
	{
		 $("#date").focus();
		return "Date is a required field";
	}
	
	
	if(food == null || food.length == 0)
	{
		$("#entry").focus();
		return "Food item is a required field";
	}
	
	
	if(cals == null || cals.length == 0)
	{
		$("#calories").focus();
		return "Calories is a required field";
	}
	
	if(!$("#calories").val().match('^(0|[1-9][0-9]*)$'))
    {
		$("#calories").focus();
        return "Calories must be numeric";
    }
	return "";
}

function onSuccessSaveItem(result)
{
	 var json = JSON.parse(result);
	console.log("onSuccessSaveItem: " + result);
	onNotify("Entry has been saved " + json.title);
	$("#entryid").val(json.entryid);
	buildItems(selectedMySQLDate);
}

function onSuccessDeleteItem(result)
{
	 var json = JSON.parse(result);
	console.log("onSuccessDeleteItem: " + result);
	onNotify("Entry has been deleted");
	$("#entryid").val(json.entryid);
	buildItems(selectedMySQLDate);
}



function onSaveError (xhr, ajaxOptions, thrownError) 
{
	alert(thrownError);
}

function getMySQLDate(dt)
{
	console.log("getMySQLDate: " + dt);
	dateFields = dt.split(' ');
	if(dateFields.length != 3)
		return "-1";
	console.log(dateFields.length);
	console.log(dateFields[0]);
	var mySQLMonth = getMonthFromText(dateFields[0]);
	var result = dateFields[2] + "-" +  mySQLMonth + "-" + dateFields[1];
	console.log(result);
	return result;
}

function getMonthFromText(arg)
{
  var s = arg.toUpperCase();
  var sub1 = s.substring(0, 1);
  console.log(sub1);
  if(sub1 == "D")
	  return 12;
  if(sub1 == "F")
	  return 2;
  if(sub1 == "S")
	  return 9;
  if(sub1 == "O")
	  return 10;
  if(sub1 == "N")
	  return 11;
  var sub2 = s.substring(0, 3);
  console.log(sub2);
  if(sub2 == "JAN")
	  return 1;
  if(sub2 == "JUN")
	  return 6;
  if(sub2 == "JUL")
	  return 7;
  if(sub2 == "APR")
	  return 4;
  if(sub2 == "MAR")
	  return 3;
  if(sub2 == "MAY")
	  return 5;
  if(sub2 == "AUG")
	  return 8;
  return "-1";
}

function buildItems(date)
{
	console.log("buildItems: " + date);
	$.ajax({
		  type: "GET",
		  url: "/CalorieCounterService/GetEntries.php?token=" + token + "&date=" + date,
		  data: 
		  {
			  
		  },
	      success: onGetItemsResult,
	      error: onGetItemsError
		  });
}

function onGetItemsResult(json)
{
  console.log("onGetItemsResult" + json);
  $("#entries").html("");
  var entries = JSON.parse(json);
  var totalCalories=0;
  var currentDate="";
  //console.log(dayVO);
  //console.log(result["date"]);
  //console.log(dayVO.items.length);

  $.each(entries, function(index, item) {
	  //console.log(bob);
	  if(currentDate == "")
		  currentDate = item.date;
	  $("#entries").append(getItemLayout(item));
	  totalCalories += parseInt(item.calories);
	});
  
  //$("#dayHeader").html("Entries for " + currentDate);
  
  var totalLine = new Object();
  totalLine.title ="";
  totalLine.calories = totalCalories;
  $("#entries").append(getItemLayout(totalLine));
	
}

function onGetItemsError (xhr, ajaxOptions, thrownError) 
{
	alert(thrownError);
}

function getItemLayout(entry)
{
  console.log("getItemLayout: " + entry.title  + " " + entry.calories);
  var layout = "<tr><td class='items'>";
  layout += "<a href='#' onclick='loadEntry(" + entry.entryid + "); return false;' style='color:#000000'>" + entry.title + "</a>";
  layout +="</td><td class='items'>"+ entry.calories + "</td></tr>";
  return layout;
}

function loadEntry(id)
{
	$.ajax
	(
		{
		  type: "GET",
		  url: "/CalorieCounterService/GetEntry.php?token=" + token + "&entryid=" +id,
		  data: 
		  {
			  
		  },
	      success: onGetEntryResult,
	      error: onGetItemsError
		}
	);
}

function onGetEntryResult(entryObject)
{
  $("#btnDelete").css("display", "inline");
  entryObject = JSON.parse(entryObject);
  console.log(entryObject);
  $("#date").val(entryObject.date);
  $("#entry").val(entryObject.title);
  $("#entryid").val(entryObject.entryid);
  $("#notes").val(entryObject.notes);
  $("#calories").val(entryObject.calories);
  $("#carbs").val(entryObject.carbs);
  
}

function onNewItem()
{
	displayDate = getMonthDescr(now.getMonth() + 1) + " " + now.getDate() + " " + now.getFullYear();
	$("#btnDelete").css("display", "none");
	$("#date").val(displayDate);
	$("#entry").val("");
	$("#entryid").val(0);
	$("#notes").val("");
	$("#calories").val(0);
	$("#carbs").val(0);
}

function onDeleteItem()
{
	var id = $("#entryid").val();
	if(id == null || id == undefined || id < 1)
		alert("improper request");
	else 
	{
	
		if( confirm("Are you sure you want to delete this entry?"))
		{
			onNewItem();
			$.ajax({
				  type: "DELETE",
				  url: "/CalorieCounterService/DeleteEntry.php?token=" + token + "&entryid=" +id,
				  data: 
				  {
					  
				  },
			      success: onSuccessDeleteItem,
			      error: onGetItemsError
				  });
		}
		
	}
}

function getMonthDescr(mm)
{
  switch(mm)
  {
  
  case 1:
	  return "January";
  case 2:
	  return "February";
  case 3:
	  return "March";
  case 4:
	  return "April";
  case 5:
	  return "May";
  case 6:
	  return "June";
  case 7:
	  return "July";
  case 8:
	  return "August";
  case 9:
	  return "September";
  case 10:
	  return "October";
  case 11:
	  return "November";
  case 12:
	  return "December";
  
  }
}

function onCloseNotification()
{
	$("#notificationBarWrapper").css("display", "none");
	$("#notificationCloseButton").css("display", "none");
	window.clearInterval(notifyTimer);
}

function onNotify(arg)
{
	
	$("#notificationBarWrapper").html(arg);
	$("#notificationBarWrapper").css("display", "block");
	$("#notificationCloseButton").css("display", "block");
	notifyTimer = setInterval(function(){onCloseNotification()},3000);
}

function onBlur()
{
	changeTimer = setInterval(function(){onDateChange()},400);
}

function onDateChange()
{
	window.clearInterval(changeTimer);
	var date = $("#date").val();
	selectedMySQLDate = getMySQLDate(date);
	if(selectedMySQLDate == "-1")
	  alert("Invalid Date");
	else
	  buildItems(selectedMySQLDate);
}

function onFormChange()
{
 console.log("onFormChange");	
}


function onFormInput()
{
 console.log("onFormInput");	
}

function onKeyDown()
{
 console.log("onKeyDown");	
}

function onMouseOut()
{
 console.log("onMouseOut");	
}

function drawVisualization() 
{
	
	  var data = new google.visualization.DataTable();
	  data.addColumn('date', 'Date');
	  data.addColumn('number', 'Calories');
	  data.addColumn('string', 'title1');
	  data.addColumn('string', 'text1');
	  data.addColumn('number', 'Carbs');
	  data.addColumn('string', 'title2');
	  data.addColumn('string', 'text2');
	  data.addRows([
	    [new Date(2008, 1 ,1), 30000, null, null, 40645, null, null],
	    [new Date(2008, 1 ,2), 14045, null, null, 20374, null, null],
	    [new Date(2008, 1 ,3), 55022, null, null, 50766, null, null],
	    [new Date(2008, 1 ,4), 75284, null, null, 14334, 'Out of Stock', 'Ran out of stock on pens at 4pm'],
	    [new Date(2008, 1 ,5), 41476, 'Bought Pens', 'Bought 200k pens', 66467, null, null],
	    [new Date(2008, 1 ,6), 33322, null, null, 39463, null, null]
	  ]);

	  var annotatedtimeline = new google.visualization.AnnotatedTimeLine(
	      document.getElementById('chart_div'));
	  annotatedtimeline.draw(data, {'displayAnnotations': true});
}


$(document).ready(onInit());